#!/bin/bash

IPMAN_LIB_PATH=$(dirname ${BASH_SOURCE[0]})
source "${IPMAN_LIB_PATH}/config.sh"

# prints primary interface name to stdout.
# If any error occures, it prints error message to stderr and help to stdout, then terminates the process
dynamic_config_path="${1}"

config=$(ipman_read_config "${dynamic_config_path}")
if [[ ${?} -ne 0 ]]; then
    >&2 echo "Failed to read config from ${dynamic_config_path}"
    return 1
fi

interface_names=$(${IPMAN_LIB_PATH}/ipman-list-interfaces "${config}")
if [[ ${?} -ne 0 ]]; then
    >&2 echo "Failed to get interface list"
    return 1
fi

primary_interface=""
highest_prio=$(printf '%u' 0xffffffff) # start from the lowest possible prio (high number means low prio)

for interface in ${interface_names}; do
    enabled=$(${IPMAN_LIB_PATH}/ipman-show "${dynamic_config_path}" "${interface}" | jq -r '.enabled')
    if [[ "${enabled}" != "true" ]]; then
        continue
    fi
    prio=$(netman priority ${interface})
    if [[ ${?} -ne 0 ]]; then
        >&2 echo "Failed to get priority for interface ${interface}"
        return 1
    fi
    if [[ ${prio} -lt ${highest_prio} ]]; then
        highest_prio=${prio}
        primary_interface="${interface}"
    fi
done

echo "${primary_interface}"
